/**
 * 
 */
package org.mspring.mlog.service.security.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.mspring.mlog.entity.security.Resource;
import org.mspring.mlog.service.security.ResourceService;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.query.QueryCriterion;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since 2013-1-11
 * @Description
 * @TODO
 */
@Service
@Transactional
public class ResourceServiceImpl extends GenericDao implements ResourceService {

    private static final Logger log = Logger.getLogger(ResourceServiceImpl.class);

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.mlog.service.security.ResourceService#findAllResources()
     */
    @Override
    public List<Resource> findAllResources() {
        // TODO Auto-generated method stub
        return getHibernateTemplate().getAll(Resource.class);
    }

    @Override
    public Resource createResource(Resource resource) {
        // TODO Auto-generated method stub
        return (Resource) getHibernateTemplate().save(resource);
    }

    @Override
    public Resource getResourceById(Long id) {
        // TODO Auto-generated method stub
        return (Resource) getHibernateTemplate().get(Resource.class, id);
    }

    @Override
    public boolean updateResource(Resource resource) {
        // TODO Auto-generated method stub
        try {
            getHibernateTemplate().update(resource);
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }

    @Override
    public boolean deleteResource(final Long id) {
        // TODO Auto-generated method stub
        try {
            Session session = getSession();
            String deleteRoleResource = "delete from RoleResource rr where rr.PK.resource.id = ?";
            String deleteResource = "delete from Resource r where r.id = ?";
            session.createQuery(deleteRoleResource).setLong(0, id).executeUpdate();
            session.createQuery(deleteResource).setLong(0, id).executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            log.error("delete resource failure!", e);
            return false;
        }
        return true;
    }

    @Override
    public Page<Resource> findResources(QueryCriterion queryCriterion, Page<Resource> resourcePage) {
        // TODO Auto-generated method stub
        return getHibernateTemplate().listPage(queryCriterion, resourcePage);
    }

}
